package com.delivery.deliverysystem.service.impl;

import com.delivery.deliverysystem.common.DataSourceBean;
import com.delivery.deliverysystem.common.ServerResponse;
import com.delivery.deliverysystem.pojo.DAO.DetectReportDAO;
import com.delivery.deliverysystem.pojo.DAO.LabelDAO;
import com.delivery.deliverysystem.pojo.DAO.QuotationDAO;
import com.delivery.deliverysystem.pojo.DAO.ReconciliationDAO;
import com.delivery.deliverysystem.pojo.VO.CadExcelListVO;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;

@Service
public class ExcelServiceImpl {
    @Autowired
    private DataSourceBean dataSourceBean;
    @Value("${server.port}")
    private Integer port;
    public List<CadExcelListVO> readExcelFile(String filePath) throws IOException {
        List<CadExcelListVO> dataList = new ArrayList<>();
        try (Workbook workbook = new XSSFWorkbook(new FileInputStream(new File(filePath)))) {
            Sheet sheet = workbook.getSheetAt(0);
            int rows = sheet.getLastRowNum(); // 获取所有的行

            for (int i = 1; i <= rows; i++) { // 从第二行开始录入数据（索引从1开始）
                Row row = sheet.getRow(i);
                if (row == null) {
                    continue; // 如果遇到空行，则跳过
                }
                CadExcelListVO data = new CadExcelListVO();
                data.setBladeMouldNumber(getStringCellValue(row.getCell(0)));
                data.setBladeMouldName(getStringCellValue(row.getCell(1)));
                data.setBladeTotalLength(getNumericCellValue(row.getCell(2)));
                data.setCircleRadius(getNumericCellValue(row.getCell(3)));
                data.setRectangleLengthWidth(getNumericCellValue(row.getCell(4)));
                data.setAlienLengthWidth(getNumericCellValue(row.getCell(5)));
                data.setLineLength(getNumericCellValue(row.getCell(6)));
                data.setPunchingHole(getNumericCellValue(row.getCell(7)));
                data.setBladeLength(getNumericCellValue(row.getCell(8)));
                data.setBladeWidth(getNumericCellValue(row.getCell(9)));
                data.setBladeTemplateArea(getNumericCellValue(row.getCell(10)));
                data.setLocatingColumnCount(getIntCellValue(row.getCell(11)));
                data.setPunchingHoleCount(getIntCellValue(row.getCell(12)));
                data.setScrewHoleCount(getIntCellValue(row.getCell(13)));
                data.setWorkPieceCount(getIntCellValue(row.getCell(14)));
                data.setPunchingHoleMeters(getNumericCellValue(row.getCell(15)));
                data.setText(getStringCellValue(row.getCell(16)));
                data.setAllWork(getStringCellValue(row.getCell(17)));
                dataList.add(data);
            }
        }
        return dataList;
    }

    private String getStringCellValue(Cell cell) {
        if (cell == null) {
            return "";
        }
        switch (cell.getCellType()) {
            case STRING:
                return cell.getStringCellValue();
            case NUMERIC:
                return String.valueOf(cell.getNumericCellValue());
            default:
                return "";
        }
    }

    private double getNumericCellValue(Cell cell) {
        if (cell == null) {
            return 0;
        }
        switch (cell.getCellType()) {
            case NUMERIC:
                return cell.getNumericCellValue();
            case STRING:
                try {
                    return Double.parseDouble(cell.getStringCellValue());
                } catch (NumberFormatException e) {
                    return 0;
                }
            default:
                return 0;
        }
    }

    private int getIntCellValue(Cell cell) {
        return (int) getNumericCellValue(cell);
    }

    /**
     * 利用UReport导出对账单
     * @param reconciliationDAO
     * @return
     */
    public ServerResponse reconciliationExport(ReconciliationDAO reconciliationDAO) {
        // 准备数据源
        Map<String, Object> parameters = new HashMap<>();
        parameters.put("reconciliationDAO", reconciliationDAO);
        // 调用 DataSourceBean 的 loadPdfData 方法获取数据
        List<Map<String, Object>> reportData = dataSourceBean.loadPdfData1("dataSourceName", "dataSetName", parameters);
        String fileName = reconciliationDAO.getFullName() + reconciliationDAO.getBeginTime() + "对账单";
        String templateName = "对账单模板.ureport.xml";
        String exportUrl = "http://localhost:"+port+"/ureport/excel?_u=file:"+templateName+"&_n="+fileName;
        return ServerResponse.createBySuccess(exportUrl);
    }

    /**
     * 利用UReport导出标签表
     * @param labelDAO
     * @return
     */
    public ServerResponse labelExport(LabelDAO labelDAO) {
        // 准备数据源
        Map<String, Object> parameters = new HashMap<>();
        parameters.put("label", labelDAO);

        // 调用 DataSourceBean 的 loadPdfData2 方法获取数据
        List<Map<String, Object>> reportData = dataSourceBean.loadPdfData2("dataSourceName", "dataSetName", parameters);

        // 生成文件名
        String fileName = labelDAO.getClientName() +"标签表.xlsx";
        String templateName = "公司标签表.ureport.xml";
        // 调用 UReport2 的导出接口
        String exportUrl = "http://localhost:" + port + "/ureport/excel?_u=file:" + templateName + "&_n=" + fileName;

        // 返回导出链接
        return ServerResponse.createBySuccess(exportUrl);
    }

    /**
     * 利用UReport导出检测报告
     * @param detectReportDAO
     * @return
     */
    public ServerResponse detectReportExport(DetectReportDAO detectReportDAO) throws JsonProcessingException {
        // 准备数据源
        Map<String, Object> parameters = new HashMap<>();
        parameters.put("detect", detectReportDAO);

        // 调用 DataSourceBean 的 loadPdfData3 方法获取数据
        List<Map<String, Object>> reportData = dataSourceBean.loadPdfData3("dataSourceName", "dataSetName", parameters);

        // 生成文件名
        String fileName = detectReportDAO.getClientName() +"检测报告.xlsx";
        String templateName = "检测报告.ureport.xml";
        // 调用 UReport2 的导出接口
        String exportUrl = "http://localhost:" + port + "/ureport/excel?_u=file:" + templateName + "&_n=" + fileName;

        // 返回导出链接
        return ServerResponse.createBySuccess(exportUrl);
    }

    /**
     * 利用UReport导出报价单
     * @param quotationDAO
     * @return
     */
    public ServerResponse quotationExport(QuotationDAO quotationDAO) {
        // 准备数据源
        Map<String, Object> parameters = new HashMap<>();
        parameters.put("quotation", quotationDAO);

        // 调用 DataSourceBean 的 loadPdfData3 方法获取数据
        List<Map<String, Object>> reportData = dataSourceBean.loadPdfData4("dataSourceName", "dataSetName", parameters);

        // 生成文件名
        String fileName = quotationDAO.getProductName() +".xlsx";
        String templateName = "报价单模板.ureport.xml";
        // 调用 UReport2 的导出接口
        String exportUrl = "http://localhost:" + port + "/ureport/excel?_u=file:" + templateName + "&_n=" + fileName;

        // 返回导出链接
        return ServerResponse.createBySuccess(exportUrl);
    }
}
